from rest_framework.serializers import ModelSerializer, ValidationError
from rest_framework import serializers
from erp_system.models import UserModel
import re

# 用户注册基本的序列化类
from erp_system.serializers.roles_serialzier import RolesSerializer


class UserAddSerializer(ModelSerializer):
    """
    仅仅用于用户注册
    """

    class Meta:
        model = UserModel
        fields = ('id', 'username', 'password', 'phone', 'real_name')
        extra_kwargs = {
            'username': {
                'max_length': 12,
                'min_length': 2
            },
            'password': {
                'max_length': 8,
                'min_length': 3,
                'write_only': True

            },
        }

    def validate_phone(self, phone):
        """
        自定义验证手机号码，规则：函数名=validate_<field_name>
        """
        if not re.match(r'^1[3589]\d{9}$', phone):
            raise ValidationError("请输入正确的手机号码")
        return phone

    def create(self, validated_data):
        """重写用户注册，否则直接把明文密码保存到数据库"""
        user = UserModel.objects.create_user(**validated_data)
        return user


from rest_framework.serializers import ModelSerializer, ValidationError, CharField, ValidationError


class UserUpdateDeleteSerializer(ModelSerializer):
    """
    只用于：修改用户（修改用户的角色，修改用户的部门）和删除用户
    """

    class Meta:
        model = UserModel
        fields = ('id', 'roles', 'dept')


class ResetPasswordSerializer(ModelSerializer):
    """
    重置密码序列化器,只用与修改密码
    """
    confirm_password = CharField(write_only=True)

    class Meta:
        model = UserModel
        fields = ['id', 'password', 'confirm_password']
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def validate(self, attrs):
        # partial_update, 局部更新required验证无效, 手动验证数据
        password = attrs.get('password')
        confirm_password = attrs.get('confirm_password')
        if not password:
            raise ValidationError('字段password为必填项')
        if not confirm_password:
            raise ValidationError('字段confirm_password为必填项')
        if password != confirm_password:
            raise ValidationError('两次密码不一致')
        return attrs

    def save(self, *args):
        # 重写save方法, 保存密码
        self.instance.set_password(self.validated_data.get('password'))
        self.instance.save()
        return self.instance


class UserGetSerializer(ModelSerializer):
    """
    只用于：查询用户
    """
    roles = RolesSerializer(many=True, read_only=True)
    dept_name = serializers.CharField(source='dept.name')

    class Meta:
        model = UserModel
        fields = ('id', 'username', 'phone', 'real_name', 'roles', 'dept_name')
